package com.example.springcloud.provider.student.controller;

import com.example.springcloud.common.entity.ResponseResult;
import com.example.springcloud.common.entity.Student;
import com.example.springcloud.provider.student.service.StudentService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    private final StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @PutMapping
    public ResponseResult<?> addStudent(@RequestBody Student student) {
        try {
            studentService.addStudent(student);
        } catch (Exception e) {
            return new ResponseResult<>(500, "添加失败", null);
        }
        return new ResponseResult<>(200, "添加成功", null);
    }

    @GetMapping("/{id}")
    public ResponseResult<?> findStudent(@PathVariable int id) {
        Student student = studentService.findStudentById(id);
        return new ResponseResult<>(200, "查询成功", student);
    }

    @GetMapping
    public ResponseResult<?> findAllStudents() {
        List<Student> students;
        try {
            students = studentService.findAllStudents();
        } catch (Exception e) {
            students = null;
        }
        return new ResponseResult<>(200, "查询成功", students);
    }

    @DeleteMapping("/{id}")
    public ResponseResult<?> deleteStudent(@PathVariable("id") int id) {
        try {
            studentService.deleteStudent(id);
        } catch (Exception e) {
            return new ResponseResult<>(500, "删除失败", null);
        }
        return new ResponseResult<>(200, "删除成功", null);
    }

    @PostMapping
    public ResponseResult<?> updateStudent(@RequestBody Student student) {
        try {
            studentService.updateStudent(student);
        } catch (Exception e) {
            return new ResponseResult<>(500, "修改失败", null);
        }
        return new ResponseResult<>(200, "修改成功", null);
    }
}
